package com.gec.service.Impl;

import com.gec.dao.NotifyDao;
import com.gec.domain.Notify;
import com.gec.domain.PageBean;
import com.gec.domain.PageParam;
import com.gec.service.abst.NotifyService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

@Service
public class NotifyServiceImpl extends BaseService implements NotifyService {
    private final NotifyDao notifyDao;

    public NotifyServiceImpl(NotifyDao notifyDao) {
        this.notifyDao = notifyDao;
    }

    @Override
    public void saveNotify(Notify notify) throws Exception {
        String id = notify.getId();
        try {
            notify.setDownTimes(0);
            notify.setId(uuid());
            notifyDao.addNotify(notify);
        } catch (Exception e) {
            e.printStackTrace();
            String[][] checks = {{"uni_notifyName", "通告标题重复"}};
            checkUniqueException(e, checks);
        }

    }

    @Override
    public PageBean<Notify> getNotifyList(PageParam param) {
        int size = param.getLimit();  //页大小
        int page = param.getPage();   //页码
        //{1}在查询之前先调用这个方法来准备拦截查询
        Page<Object> pageInfo = PageHelper.startPage(page, size, true);
        //{2}调用 dao 方法来查询
        List<Notify> list = notifyDao.getNotifyList(param.getKeywords());
        PageBean pBean = new PageBean();
        int total = (int) pageInfo.getTotal();
        //{3}生成 PageBean, 再封装信息到 pBean
        pBean.setCount(total);  //总记录数
        pBean.setData(list);    //用户列表
        pBean.setCode(0);     //状态码
        return pBean;
    }

    @Override
    public void delNotify(String id) {
        Notify notify = notifyDao.getNotifyById(id);
        notifyDao.delNotify(id);
        String srcPath = "D://ttt//";
        String fileName = notify.getFileName();
        File file = new File(srcPath + fileName);
        file.delete();
    }

    @Override
    public Notify getNotifyById(String id) {
        Notify notify = null;
        try {
            notify = notifyDao.getNotifyById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return notify;
    }

    @Override
    public void downNotifyCount(Notify notify) {
        notifyDao.downNotifyCount(notify);
    }

    @Override
    public void updateNotitf(Notify notify) {
        notifyDao.updateNotify(notify);
    }
}
